package cn.ddd.linktran.domain.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.temporal.ChronoUnit;
import java.util.Date;
import java.util.Objects;

public class DateUtil {

    // 统一使用同一时区进行双向转换：使用系统默认时区
    private static final ZoneId ZONE = ZoneId.systemDefault();

    /** LocalDateTime -> epoch millis */
    public static Long dateToLong(LocalDateTime date) {
        if (Objects.isNull(date)) return 0L;
        return date.atZone(ZONE).toInstant().toEpochMilli();
    }

    /** epoch millis -> LocalDateTime */
    public static LocalDateTime longToDate(long currentTimeMillis) {
        return Instant.ofEpochMilli(currentTimeMillis).atZone(ZONE).toLocalDateTime();
    }

    public static Long dateTypeToLong(Date date) {
        if (Objects.isNull(date)) {
            return 0L;
        }

        return date.getTime();
    }

    public static Date longToDateTypr(long currentTimeMillis) {
        SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // long转Date
        Date date = null;
        try {
            date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(sd.format(new Date(currentTimeMillis)));
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        return date;
    }

}
